package cn.acewill.yxd.yunxundian.pubClass;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.departBean;
import cn.acewill.yxd.yunxundian.model.deviceTask;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.r_reportrowAddtion;
import cn.acewill.yxd.yunxundian.model.r_rrowAddtion_item;
import cn.acewill.yxd.yunxundian.model.reportHeadBean;
import cn.acewill.yxd.yunxundian.model.reportTailBean;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tReportHead;
import cn.acewill.yxd.yunxundian.model.tReportTail;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Main;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row_History;
import cn.acewill.yxd.yunxundian.model.t_Feedback_attachment;
import cn.acewill.yxd.yunxundian.model.t_Feedback_attachment_history;
import cn.acewill.yxd.yunxundian.ui.SynchronizationAtivity;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by he on 2017/4/6.
 * 同步数据所用
 */

public class AsynData {

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    public static int doneNum=0;
    public static final int maxDone=5;
    private ProgressDialog dialog;
    private Context context;
    private Handler mHandler;

    public AsynData(Handler mHandler){
        this.mHandler = mHandler;
    }

    protected void AsynData(){
        SharedPreferences sp = context.getSharedPreferences("yxdUrl",MODE_PRIVATE);
        String name =sp.getString("IpName","");
        String branchName = sp.getString("branchName","");
        String ip = "http://"+(name)+"/"+(branchName)+"/appservice/appservicehzm.aspx";
    }
    //第一个方法 清空所有数据 然后将服务器消息同步过来
    public int aDataForFirstUse(int Employeeid)
    {
        return 0;
    }

    public void clearEmployee() throws DbException {
        try {
            db.delete(Employee.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void clearShop() throws DbException{
        try {
            db.delete(Employee.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void clearSchedule() throws DbException{
        try {
            db.delete(Schedule.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void clearRJSON() throws DbException{
            db.delete(rJson.class);
    }

    //region 同步签到信息
    public int asynSignUpData(int employeeid) throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","getSignupInfoByEmpid");
        map.put("empid",String.valueOf(employeeid));
        okhttp3.Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            asynSignUpData(result);
            doneNum=doneNum+1;
        }
//        pubClass.Post(url,map,new pubClass.MyCallBack<String>(){
//            @Override
//            public void onSuccess(String result) {
//
//            }
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                super.onError(ex, isOnCallback);
//            }
//        });
        return 0;
    }

    private void asynSignUpData(String result)
    {
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynSignUpData","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<SignUpInfo>>() {
            }.getType();
            ArrayList<SignUpInfo> shops = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (SignUpInfo ee:shops
                    ) {
                try {
                    SignUpInfo dbShop = db.selector(SignUpInfo.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbShop!=null)
                    {
                        ee.set_ID(dbShop.get_ID());
                        db.saveOrUpdate(ee);
                    }
                    else
                        db.saveOrUpdate(ee);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    //endregion

    //region 1.同步人员信息

    public int asynEmployeeData(int employeeid) throws IOException {

        Map<String,String> map=new HashMap<>();
        map.put("task","getEmployeeById");
        map.put("userid",String.valueOf(employeeid));

        okhttp3.Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);

        if (response.isSuccessful()){
           String responStr=response.body().string();

            asynEmpData(responStr);
            doneNum=doneNum+1;
            return 1;
        }
        else{
            return 0;
        }
    }


    public int asynEmployeeDatax(int employeeid) throws IOException {

        Map<String,Object> map=new HashMap<>();
        map.put("task","getEmployeeById");
        map.put("userid",String.valueOf(employeeid));
        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onSuccess(String result) {
                asynEmpData(result);
                doneNum=doneNum+1;
            }
        });
        return 0;
    }

    private  void asynEmpData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("emplee","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<Employee>>() {
            }.getType();
            ArrayList<Employee> emps = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (Employee ee:emps) {
                try {
                    Employee dbEmp = db.selector(Employee.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbEmp!=null)
                    {
                        ee.set_ID(dbEmp.get_ID());
                        db.saveOrUpdate(ee);
                    }
                    else
                        db.saveOrUpdate(ee);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
            Type cmbList = new TypeToken<ArrayList<CommonMapBean>>() {
            }.getType();
            ArrayList<CommonMapBean> cmbs=gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[1]), cmbList);
            for(CommonMapBean cmb :cmbs)
            {
                try {
                    CommonMapBean dbCmb = db.selector(CommonMapBean.class).
                            where("cmType", "=",cmb.getCmType())//role
                            .and("ServerId","=",cmb.getServerId())//人员id
                            .and("indexNum","=",cmb.getIndexNum())//role的id
                            .and("cmValue","=",cmb.getCmValue())//rolename
                            .findFirst();
                    if(dbCmb!=null)
                    {
                        cmb.set_ID(dbCmb.get_ID());
                        db.saveOrUpdate(cmb);
                    }
                    else
                        db.saveOrUpdate(cmb);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    //endregion

    //region 同步门店信息
    public int asynShopData(int employeeid) throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","getShopByEmployeeID");
        map.put("empid",String.valueOf(employeeid));
        okhttp3.Response respons=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (respons.isSuccessful()){
            String responStr=respons.body().string();
            asynShopData(responStr);
            doneNum=doneNum+1;
        }
        return 0;
    }

    private void asynShopData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynShopData","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<Shop>>() {
            }.getType();
            ArrayList<Shop> shops = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (Shop ee:shops
                    ) {
                try {
                    Shop dbShop = db.selector(Shop.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbShop!=null)
                    {
                        ee.set_ID(dbShop.get_ID());
                        db.saveOrUpdate(ee);
                    }
                    else
                        db.saveOrUpdate(ee);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    //endregion

    //region 日程信息同步
    public int asynScheduleData(int employeeid) throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadScheduleByEmpId");
        map.put("empid",String.valueOf(employeeid));
        Response respons=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (respons.isSuccessful()) {
            String responStr = respons.body().string();
            asynScheduleData(responStr);
            doneNum=doneNum+1;
        }
        return 0;
    }

    //异步请求日程
    public int asyScheduleByEscute(int employeeid){
         int value = 201;
        Map<String,String> map=new HashMap<>();
        map.put("task","loadScheduleByEmpId");
        map.put("empid",String.valueOf(employeeid));
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    asynScheduleData(result);
                }

                @Override
                public void onFailture() {
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
      return 200;
    }




    //loadOtherOESchedule
    public int asynOEScheduleData(int employeeid) throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadOtherOESchedule");
        map.put("empid",String.valueOf(employeeid));
        Response respons=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (respons.isSuccessful()) {
            String responStr = respons.body().string();
            asynScheduleData(responStr);
            doneNum=doneNum+1;

        }

        return 0;
    }

    public void asynScheduleData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynScheduleData","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<Schedule>>() {
            }.getType();
            ArrayList<Schedule> Schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (Schedule ee:Schedules) {
                try {
                    Schedule dbSch = db.selector(Schedule.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbSch!=null)//如果服务器端的任务已经是先于本地端 则更新本地数据。
                    {
                        if(ee.getStates()>dbSch.getStates()){
                        ee.set_ID(dbSch.get_ID());
                        db.saveOrUpdate(ee);
                        }
                    }
                    else
                        db.saveOrUpdate(ee);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }

            Type cmtype=new TypeToken<ArrayList<CommonMapBean>>(){}.getType();
            try {
                ArrayList<CommonMapBean> fenshuList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[1]), cmtype);
                for (CommonMapBean tcm : fenshuList) {
                    try {
                        CommonMapBean fenshub = db.selector(CommonMapBean.class).where("CmType", "=", "fenshu").and("ServerId", "=", tcm.getServerId() + "").findFirst();
                        if (fenshub != null) {
                            tcm.set_ID(fenshub.get_ID());
                            db.saveOrUpdate(tcm);
                        } else {
                            db.saveOrUpdate(tcm);
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }
            catch (Exception e)
            {

            }
        }
    }

    public int asynScheduleDataWithCallBack(int employeeid, Callback.CommonCallback<String> callback) {
        Map<String,Object> map=new HashMap<>();
        map.put("task","loadScheduleByEmpId");
        map.put("empid",String.valueOf(employeeid));
        pubClass.Post(pubClass.Server_namehzm,map,callback);
        return 0;
    }

    //endregion

    //region 同步stype
    public int asynStypeData() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadsTypes");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            asynStypeData(result);
            doneNum=doneNum+1;
        }
        return 0;
    }

    private void asynStypeData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynStypeData","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<sType>>() {
            }.getType();
            ArrayList<sType> stype = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (sType ee:stype) {
                try {
                    sType dbSch = db.selector(sType.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbSch!=null)//如果服务器端的任务已经是先于本地端 则更新本地数据。
                    {
                        ee.set_ID(dbSch.get_ID());
                        db.saveOrUpdate(ee);
                    }
                    else {
                        db.saveOrUpdate(ee);
                    }
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }

        }
    }

    public int asynRMData() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadRMain");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            asynRMData(result);
        }
        return 0;
    }

    private void asynRMData(String result) throws IOException {
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynRMData","success");
            String[] rmids = resArry[3].split(",");
            for (String s:rmids
                    ) {
                try {
                    rJson dbSch = db.selector(rJson.class).where("id", "=", s).findFirst();
                    if(dbSch!=null)//如果服务器端的任务已经是先于本地端 则更新本地数据。
                    {
                        continue;
                    }
                    else {
                        asynRMDataDetail(s);
                    }
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }


    public int asynDeviceTaskasynDeviceTask(String empid) throws IOException{
        Map<String,String> map=new HashMap<>();
        map.put("task","loadDeviceTaskByEmpid");
        map.put("empid",empid);
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            String[] resArry= result.split("\\|");//TODO 请求结果201
            if(resArry[0].equals("200")) {
                Log.e("asynDeviceTask","success");
                Gson gson = new Gson();
                //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
                Type taskList = new TypeToken<ArrayList<deviceTask>>() {
                }.getType();
                ArrayList<deviceTask> deviceTasksList = gson.fromJson(pubClass.convertToArrayJson(result), taskList);
                if (deviceTasksList == null)
                    return 0;
                for (deviceTask dTask : deviceTasksList) {
                    switch (dTask.getTasktype()) {
                        case "delsch": {
                            String retData = "";
                            Schedule ss = db.selector(Schedule.class).where("ID", "=", dTask.getDataStr()).findFirst();
                            if (ss != null) {
                                retData = retData + dTask.getId() + ",";
                                db.delete(ss);
                            }
                            Map<String, String> mapSub = new HashMap<>();
                            if (!retData.equals("")) {
                                retData = retData.substring(0, retData.length() - 1);
                            }
                            mapSub.put("task", "doneDeviceTaskByIds");
                            mapSub.put("dtids", retData);
                            Response responseSub = OkHttpManger.getInstance().postSync(pubClass.Server_namehzm, mapSub);
                            if (responseSub.isSuccessful()) {
                                Log.e("doneDeleteByRetData", "success");
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }

    public int asynRMDataDetail(String rmid) throws IOException {
        Map<String,String> map=new HashMap<>();
        final String _rmid=rmid;
        map.put("task","loadRMainDetail");
        map.put("rmid",rmid);
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            Log.e("asynRMDataDetail","success");
            asynRMDataDetailCallback(_rmid,result);
        }
        return 0;
    }





    public void asynRMDataDetailCallback(String rmid,String result) {
        rJson newRj = new rJson();
        newRj.setId(Integer.parseInt(rmid));
        newRj.setjSon(result);
        try {
            db.saveOrUpdate(newRj);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //endregion

    //region 同步部门信息
    public int asynDepartData() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","getdepart");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            asynDepartData(result);
        }

        return 0;
    }

    private void asynDepartData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.e("asynDepartData","success");
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<departBean>>() {
            }.getType();
            ArrayList<departBean> shops = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (departBean ee:shops) {
                try {
                    departBean dbDep = db.selector(departBean.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if(dbDep!=null)
                    {
                        ee.set_ID(dbDep.get_ID());
                        db.saveOrUpdate(ee);
                    }
                    else
                        db.saveOrUpdate(ee);
                }
                catch (DbException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    //endregion

    //region 同步细项附加项

    private void loadRowAddtion(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")){
            Log.i("asynRowAddtion","success");
            Gson gson = new Gson();
            Type rraType = new TypeToken<ArrayList<r_reportrowAddtion>>(){}.getType();
            ArrayList<r_reportrowAddtion> rraList=gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[3]), rraType);
            for (r_reportrowAddtion rra:rraList) {
                try {
                    r_reportrowAddtion rraQuery = db.selector(r_reportrowAddtion.class).where("Id", "=", rra.getId()).findFirst();
                    if(rraQuery!=null) {
                        rra.set_ID(rraQuery.get_ID());
                    }
                    db.saveOrUpdate(rra);
                    //Log.i("xutilsDB",rra.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            Type rra_iType = new TypeToken<ArrayList<r_rrowAddtion_item>>(){}.getType();
            ArrayList<r_rrowAddtion_item> rra_iList=gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[1]), rra_iType);
            for (r_rrowAddtion_item rra_i:rra_iList) {
                try {
                    r_rrowAddtion_item rra_iQuery = db.selector(r_rrowAddtion_item.class).where("Id", "=", rra_i.getId()).findFirst();
                    if(rra_iQuery!=null) {
                        rra_i.set_ID(rra_iQuery.get_ID());
                    }
                    db.saveOrUpdate(rra_i);
                    //Log.i("xutilsDB",rra_i.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean isLocalDataNewer(String localTime, String serverTime){
        boolean ret = false;
        if(serverTime!=null && serverTime.length()>=19 && localTime!=null && localTime.length()>=19){
            ret = localTime.substring(0,19).compareTo(serverTime.substring(0,19))>0;
            //Log.i("isLocalDataNewer",localTime.substring(0,19)+", "+serverTime.substring(0,19)+", "+ret);
        }
        return ret;
    }

    private void loadAllFeedBackData(String result){
        String[] resArry= result.split("\\|");
        if(resArry[0].equals("200")) {
            Log.i("loadAllFeedBackData","success");
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
            Type tfmType = new TypeToken<ArrayList<t_Feedback_Main>>() {
            }.getType();
            ArrayList<t_Feedback_Main> tfmList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[1]), tfmType);
            for (t_Feedback_Main tfm : tfmList) {
                try {
                    t_Feedback_Main tfmQuery = db.selector(t_Feedback_Main.class).where("Id", "=", tfm.getId()).findFirst();
                    if (tfmQuery != null) {
                        tfm.set_ID(tfmQuery.get_ID());
                    }
                    db.saveOrUpdate(tfm);
                    //Log.i("xutilsDB", tfm.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            Type tfrType = new TypeToken<ArrayList<t_Feedback_Row>>() {
            }.getType();
            try {
                ArrayList<t_Feedback_Row> tfrList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[2]), tfrType);
                for (t_Feedback_Row tfr : tfrList) {
                    t_Feedback_Row tfrQuery = db.selector(t_Feedback_Row.class).where("Id", "=", tfr.getId()).findFirst();
                    if (tfrQuery != null) {
                        if (isLocalDataNewer(tfrQuery.getlastupdate(), tfr.getlastupdate()))
                            continue;
                        tfr.set_ID(tfrQuery.get_ID());
                        tfr.setisTrrInfoLoaded(tfrQuery.getisTrrInfoLoaded());
                        tfr.settrrDesc(tfrQuery.gettrrDesc());
                        tfr.settrrFiles(tfrQuery.gettrrFiles());
                        tfr.setunULCount(tfrQuery.getunULCount());
                    }
                    db.saveOrUpdate(tfr);
                    //Log.i("xutilsDB", tfr.toString());
                }
            }catch (DbException e) {
                e.printStackTrace();
            }
            Type tfaType = new TypeToken<ArrayList<t_Feedback_attachment>>() {
            }.getType();
            ArrayList<t_Feedback_attachment> tfaList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[3]), tfaType);
            for (t_Feedback_attachment tfa : tfaList) {
                try {
                    t_Feedback_attachment tfaQuery = db.selector(t_Feedback_attachment.class).where("fileName", "=", tfa.getfileName()).findFirst();
                    if (tfaQuery != null) {
                        tfa.set_ID(tfaQuery.get_ID());
                        tfa.setlocalFilePath(tfaQuery.getlocalFilePath());
                    }
                    tfa.setisUploaded(1);
                    db.saveOrUpdate(tfa);
                    //Log.i("xutilsDB", tfa.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            Type tfrhType = new TypeToken<ArrayList<t_Feedback_Row_History>>() {
            }.getType();
            ArrayList<t_Feedback_Row_History> tfrhList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[4]), tfrhType);
            for (t_Feedback_Row_History tfrh : tfrhList) {
                try {
                    t_Feedback_Row_History tfrhQuery = db.selector(t_Feedback_Row_History.class).where("Id", "=", tfrh.getId()).findFirst();
                    if (tfrhQuery != null) {
                        tfrh.set_ID(tfrhQuery.get_ID());
                    }
                    db.saveOrUpdate(tfrh);
                    //Log.i("xutilsDB", tfrh.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            Type tfahType = new TypeToken<ArrayList<t_Feedback_attachment_history>>() {
            }.getType();
            ArrayList<t_Feedback_attachment_history> tfahList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[5]), tfahType);
            for (t_Feedback_attachment_history tfah : tfahList) {
                try {
                    t_Feedback_attachment_history tfahQuery = db.selector(t_Feedback_attachment_history.class).where("Id", "=", tfah.getId()).findFirst();
                    if (tfahQuery != null) {
                        tfah.set_ID(tfahQuery.get_ID());
                    }
                    db.saveOrUpdate(tfah);
                    //Log.i("xutilsDB", tfah.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            Type empType = new TypeToken<ArrayList<Employee>>() {
            }.getType();
            ArrayList<Employee> empList = gson.fromJson(pubClass.convertToArrayJsonNormal(resArry[6]), empType);
            for (Employee emp : empList) {
                try {
                    Employee empQuery = db.selector(Employee.class).where("ID", "=", emp.getID()).findFirst();
                    if (empQuery != null) {
                        emp.set_ID(empQuery.get_ID());
                    }
                    db.saveOrUpdate(emp);
                    //Log.i("xutilsDB", tfah.toString());
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void asynData(final int taskIndex){
        Map<String,String> map=new HashMap<>();
        map.put("task", SynchronizationAtivity.taskType[taskIndex]);

        pubClass.Get(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                //Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
                switch(taskIndex){
                    case 0:
                        loadRowAddtion(result);
                        break;
                    case 1:
                        loadAllFeedBackData(result);
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "链接请求已取消", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                if(mHandler!=null) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = taskIndex;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }
    //endregion

    //region 获取所有
    public void uploadToken(String empid,String token) throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","updateUpushToken");
        map.put("empid", empid);
        map.put("token",token);
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            //String result=response.body().string();
            //asynShopData(result);
            doneNum=doneNum+1;
        }
    }
    //更新reportHean数据
    public void asyReportHead() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadReportHead");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
           String[] arry = result.split("\\|");
            if (arry[0].equals("200")){
                Log.e("asyReportHead","success");
                Gson gson = new Gson();
                Type typeList = new TypeToken<ArrayList<reportHeadBean>>() {
                }.getType();
                ArrayList<reportHeadBean> headBeen = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                for (reportHeadBean head : headBeen){
                   reportHeadBean re= db.selector(reportHeadBean.class).where("ID","=",head.getID()).findFirst();
                    if (re!=null){
                        head.set_ID(re.get_ID());
                        db.saveOrUpdate(head);
                    }else{
                        db.saveOrUpdate(head);
                    }
                }
            }
        }

    }
    //更新reportTail数据
    private void asyReportTail() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadReportTail");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            String[] arry = result.split("\\|");
            if (arry[0].equals("200")){
                Log.e("asyReportTail","success");
                Gson gson = new Gson();
                Type typeList = new TypeToken<ArrayList<reportTailBean>>() {
                }.getType();
                ArrayList<reportTailBean> tailBeen = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                for (reportTailBean head : tailBeen){
                    reportTailBean re= db.selector(reportTailBean.class).where("ID","=",head.getID()).findFirst();
                    if (re!=null){
                        head.set_ID(re.get_ID());
                        db.saveOrUpdate(head);
                    }else{
                        db.saveOrUpdate(head);
                    }
                }
            }
        }
    }
    private void asytReportHead() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadtReportHead");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            String[] arry = result.split("\\|");
            if (arry[0].equals("200")){
                Log.e("asytReportHead","success");
                Gson gson = new Gson();
                Type typeList = new TypeToken<ArrayList<tReportHead>>() {
                }.getType();
                ArrayList<tReportHead> tailBeen = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                for (tReportHead head : tailBeen){
                    tReportHead re= db.selector(tReportHead.class).where("ID","=",head.getID()).findFirst();
                    if (re!=null){
                        head.set_ID(re.get_ID());
                        db.saveOrUpdate(head);
                    }else{
                        db.saveOrUpdate(head);
                    }
                }
            }
        }
    }
    public void asytReportTali() throws IOException {
        Map<String,String> map=new HashMap<>();
        map.put("task","loadtReportTail");
        Response response=OkHttpManger.getInstance().postSync(pubClass.Server_namehzm,map);
        if (response.isSuccessful()){
            String result=response.body().string();
            String[] arry = result.split("\\|");
            if (arry[0].equals("200")){
                Log.e("asytReportTail","success");
                Gson gson = new Gson();
                Type typeList = new TypeToken<ArrayList<tReportTail>>() {
                }.getType();
                ArrayList<tReportTail> tailBeen = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                for (tReportTail head : tailBeen){
                    tReportTail re= db.selector(tReportTail.class).where("ID","=",head.getID()).findFirst();
                    if (re!=null){
                        head.set_ID(re.get_ID());
                        db.saveOrUpdate(head);
                    }else{
                        db.saveOrUpdate(head);
                    }
                }
            }
        }
    }


    //返回一个结果
    public boolean freshMyData(int userId) throws IOException {

        asynEmployeeData(userId);
        for(int i=0;i<SynchronizationAtivity.taskType.length;i++){
            asynData(i);
        }
        asynScheduleData(userId);
        asynShopData(userId);
        asynRMData();
        asynDepartData();
        asynSignUpData(userId);
        asynStypeData();
        asynRMDataDetail(String.valueOf(userId));
        asynDeviceTaskasynDeviceTask(userId+"");
        asyReportHead();
        asyReportTail();
      //  asytReportHead();
     //   asytReportTali();
        //asynRMDataDetail(String.valueOf(userId));
        uploadToken(String.valueOf(userId),YXDAPP.token);
        db.selector(CommonMapBean.class);
        return true;
    }
}
